import React, { useState, useEffect, useRef } from "react";
import "./index.less";
import { useTranslation, Trans } from "react-i18next";
import { useNavigate, useParams, useLocation } from "react-router-dom";
import { Button, Input, Anchor, message, Popover, Collapse, Carousel, Dropdown, Statistic, Modal } from "antd";
import { DotLoader } from 'react-spinners';
import CountUp from 'react-countup';
import {
  RightOutlined,
  PlusOutlined
} from "@ant-design/icons";
import "animate.css";
import WOW from "wow.js";
import NFT from "@/assets/images/NFT.png";
import icon4 from "@/assets/images/icon4.png";
import icon5 from "@/assets/images/icon5.png";
import icon6 from "@/assets/images/icon6.png";

import { useAppKitAccount, useAppKit, useAppKitNetwork, useWalletInfo } from "@reown/appkit/react";
import { base, sepolia } from '@reown/appkit/networks'
import { tokenAbi, RWAABI, RWA500ABI } from "@/web3/ido.js";
import { useAccount, useSignMessage, useDisconnect, useReadContract, useBalance, useWriteContract, useWaitForTransactionReceipt, useSwitchChain, useBlockNumber, useSendTransaction, useSimulateContract } from 'wagmi'
import { parseEther, parseUnits, parseGwei, formatEther, formatUnits } from 'viem';
import { useQueryClient } from '@tanstack/react-query'
import { CopyToClipboard } from 'react-copy-to-clipboard';
import dayjs from "dayjs";

import utc from "dayjs/plugin/utc";
dayjs.extend(utc)
const { Link } = Anchor;

const Index = () => {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  const [tabIndex, setTabIndex] = useState(1);
  const [payNumber, setPayNumber] = useState(1);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const RWA_CONTRACT_ADDRESS = import.meta.env.VITE_RWA_CONTRACT_ADDRESS;
  const RWA_CONTRACT500_ADDRESS = import.meta.env.VITE_RWA_CONTRACT500_ADDRESS;
  const UDSC_APPROVE_CONTRACT_ADDRESS = import.meta.env.VITE_UDSC_APPROVE_CONTRACT_ADDRESS;
  const TOKEN_ADDRESS = import.meta.env.VITE_TOKEN_ADDRESS;
  const chainIdOwn = Number(import.meta.env.VITE_CHAIN_ID_RWA)
  const USDC_DECIMAL = Number(import.meta.env.VITE_USDC_DECIMAL)
  const DEAI_DECIMAL = Number(import.meta.env.VITE_DEAI_DECIMAL)
  const NODE_ENV = import.meta.env.VITE_NODE_ENV;

  const { open, close } = useAppKit()
  const { caipNetwork, caipNetworkId, chainId, switchNetwork } = useAppKitNetwork()
  const { address, isConnected, caipAddress, status } = useAppKitAccount()
  const queryClient = useQueryClient()
  const { data: blockNumber } = useBlockNumber({ watch: true })
  const { writeContract, error, data: writeData, success } = useWriteContract();
  const { writeContract: writeContractUsdc, error: errorUsdc, data: writeDataUsdc } = useWriteContract();
  const isApprovedString = useRef(0);

  const result = useWaitForTransactionReceipt({
    hash: writeData,
    chainId: chainIdOwn,
    confirmations: 1,
  })
  const resultUsdc = useWaitForTransactionReceipt({
    hash: writeDataUsdc,
    chainId: chainIdOwn,
    confirmations: 1,
  })
  //余额 
  const { data: balanceUSDC, queryKey: queryKey } = useBalance({
    address: address,
    chainId: chainIdOwn,
    token: TOKEN_ADDRESS,
  });
  const { data: isApprovedUSDC, queryKey: queryKey1 } = useReadContract({
    address: TOKEN_ADDRESS,
    abi: tokenAbi,
    functionName: 'allowance',
    chainId: chainIdOwn,
    args: [address, UDSC_APPROVE_CONTRACT_ADDRESS]
  })
  const { data: infoData, queryKey: queryKey2 } = useReadContract({
    address: RWA_CONTRACT500_ADDRESS,
    abi: RWA500ABI,
    functionName: 'info',
    chainId: chainIdOwn,
  })
  const { data: infoPartner, queryKey: queryKey3 } = useReadContract({
    address: RWA_CONTRACT500_ADDRESS,
    abi: RWA500ABI,
    functionName: 'getPartner',
    chainId: chainIdOwn,
    args: [address]
  })
  useEffect(() => {
    const timeout = setTimeout(() => {
      console.log("infoData", infoData)
      console.log("infoPartner", infoPartner)
    }, 300);
    return () => clearTimeout(timeout);
  }, [infoData, infoPartner]);
  useEffect(() => {
    const timeout = setTimeout(() => {
      if (chainId) {
        if (chainId != Number(chainIdOwn)) {
          switchNetwork(NODE_ENV === "dev" ? sepolia : base)
        }
      }
    }, 300);
    return () => clearTimeout(timeout);
  }, [chainId]);
  useEffect(() => {
    queryClient.invalidateQueries({ queryKey: queryKey })
    queryClient.invalidateQueries({ queryKey: queryKey1 })
    queryClient.invalidateQueries({ queryKey: queryKey2 })
    queryClient.invalidateQueries({ queryKey: queryKey3 })
  }, [blockNumber, queryClient])
  useEffect(() => {
    const timeout = setTimeout(async () => {
      if (error) {
        setLoading(false)
        let str = JSON.parse(JSON.stringify(error).replace(/\n/g, ""));
        message.warning(str.shortMessage);

      }

    }, 300);
    return () => clearTimeout(timeout);
  }, [error]);
  useEffect(() => {
    const timeout = setTimeout(async () => {

      if (errorUsdc) {
        setLoading(false)
        let str = JSON.parse(JSON.stringify(errorUsdc).replace(/\n/g, ""));
        message.warning(str.shortMessage);

      }

    }, 300);
    return () => clearTimeout(timeout);
  }, [errorUsdc]);
  useEffect(() => {
    const timeout = setTimeout(async () => {
      if (result?.status === "success") {
        if (isApprovedString.current === 1) {
          isApprovedString.current = 0;
          sendTransactionUsdc()
        }
      }
      if (result?.status === "error") {
        message.error(t("error"));
        setLoading(false)

      }
    }, 300);
    return () => clearTimeout(timeout);
  }, [result]);
  useEffect(() => {
    const timeout = setTimeout(async () => {
      if (resultUsdc?.status === "success") {
        message.success(t("Success"))
        setTimeout(() => {
          window.location.reload()
        }, 1000)
      }
      if (resultUsdc?.status === "error") {
        message.error(t("error"));
        setLoading(false)

      }
    }, 300);
    return () => clearTimeout(timeout);
  }, [resultUsdc]);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const changeLang = (lang) => {
    i18n.changeLanguage(lang);
    window.sessionStorage.setItem("lang", lang)
    setLangType(lang)
  }
  const saveNumberTwo = (num) => {
    if (num * 1 === 0) return 0;
    let arr = (num + "").split(".");
    if (arr.length === 2) {
      let new_num = arr[0] + "." + arr[1].substring(0, 2);
      return new_num === "0.00" ? "0" : new_num;
    } else {
      return num + ".00";
    }
  }
  const goComingSoon = () => {
    message.warn("Coming Soon")
  }
  const goOpen = (url) => {
    window.open(url)
  }
  const onChange = ({ target: { value } }) => {
    setPayNumber(parseInt(value) > 0 ? parseInt(value) : "")
  }
  const tapPay = () => {
    if (!address) return
    let price = Number(formatUnits(infoData[1], DEAI_DECIMAL));
    if (price * payNumber > Number(balanceUSDC?.formatted)) {
      return message.warn(t("Insufficient Balance"))
    }

    if (infoPartner === "0x0000000000000000000000000000000000000000") {
      return message.warn(t("Please bind the inviter first"))
    }
    if ((payNumber * Number(infoData[1])) < Number(infoData[0])) {
      return message.warn(t("The USDC spent on purchasing cannot be less than") + formatUnits(infoData[0], DEAI_DECIMAL))
    }
    setLoading(true)
    console.log("isApprovedUSDC", isApprovedUSDC)
    if (Number(isApprovedUSDC) < (payNumber * Number(infoData[1]))) {
      // 授权
      isApprovedString.current = 1;
      writeContract({
        address: TOKEN_ADDRESS,
        abi: tokenAbi,
        functionName: "approve",
        chainId: chainIdOwn,
        args: [UDSC_APPROVE_CONTRACT_ADDRESS, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"]
      })
    } else {
      sendTransactionUsdc()
    }
  }
  const sendTransactionUsdc = () => {
    writeContractUsdc({
      address: RWA_CONTRACT500_ADDRESS,
      abi: RWA500ABI,
      functionName: "pay",
      chainId: chainIdOwn,
      args: [payNumber * Number(infoData[1]),"nftpay500"]
    })
  }
  const goPay = () => {
    let nowtime = dayjs().utc().unix();
    let starttime = Number(infoData?.[2]);
    let endtime = Number(infoData?.[3]);
    console.log(nowtime)
    console.log(Number(infoData?.[2]))
    console.log(Number(infoData?.[3]))
    if (nowtime < Number(infoData?.[2])) {
      return message.warning(t("It's not yet time to start"))
    }
    if (nowtime > Number(infoData?.[3])) {
      return message.warning(t("Purchase has ended"))
    }
    setIsModalOpen(true)
  }
  return (
    <div className="rwa_box">
      <div className="nft_box">
        <div className="img_box">
          <div className="img2"><img src={NFT} alt="" /></div>
          <img className="icon4" src={icon4} alt="" />
        </div>
        <div className="right_box">
          <img className="icon6" src={icon6} alt="" />

          <div className="tit2">{t("DEAI RWA nft")}</div>
          <div className="tips">{t("tips1")}</div>
          <div className="tips">{t("tips2")}</div>
          <div className="price">{infoData ? formatUnits(infoData[1], DEAI_DECIMAL) : 0} USDC / {t("leaf")}</div>
          <div className="time">{t("starttime")} {dayjs(Number(infoData?.[2]) * 1000).utc().format("YYYY-MM-DD HH:mm:ss")}</div>
          <div className="time">{t("endtime")}  {dayjs(Number(infoData?.[3]) * 1000).utc().format("YYYY-MM-DD HH:mm:ss")}</div>
          <div className="btn_box">
            <Button type="primary" className="btn" onClick={goPay}>{t("pay")}</Button>
            {/* <Button type="primary" className="btn" >{t("Upgrading")}</Button> */}
            <img className="icon5" src={icon5} alt="" />
          </div>
        </div>
      </div>
      <Modal title="" centered open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
        <div className="modal_box">
          <div className="flex">
            <div className="left_box">
              {t("Buy Cards")}
            </div>
            <div className="right_box">
              <div className="balance">{t("Available USDC")}：<span>{saveNumberTwo(balanceUSDC?.formatted || 0)}</span></div>
            </div>
          </div>
          <div className="input_box">
            <Input className="input" onChange={onChange} placeholder={t("Please enter your purchase quantity")} />
          </div>
          <div className="btn_box">
            <Button type="primary" className="btn" loading={loading} onClick={tapPay}>{t("pay")}</Button>
          </div>
        </div>
      </Modal>
    </div >
  );
};
export default Index;
